package nl.infodation.emr.pricingservice.ui;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.List;

import nl.infodation.emr.pricingservice.controller.ControllerFactory;
import nl.infodation.emr.pricingservice.controller.IController;
import nl.infodation.emr.pricingservice.data.PromotionConnectedSelection;
import nl.infodation.emr.pricingservice.ui.component.IView;
import nl.infodation.emr.pricingservice.ui.component.PagingComponent;
import nl.infodation.emr.pricingservice.ui.component.PagingModel;
import nl.infodation.emr.pricingservice.ui.page.SessionData;
import nl.infodation.emr.utility.Constants;
import nl.infodation.emr.utility.DateTimeUtil;
import nl.infodation.emr.utility.StringUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vaadin.annotations.AutoGenerated;
import com.vaadin.data.util.BeanItem;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.event.ItemClickEvent.ItemClickListener;
import com.vaadin.ui.AbsoluteLayout;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextField;

@SuppressWarnings({ "rawtypes", "unchecked", "deprecation" })
public class PromotionConnectedSelectionPopup extends CustomComponent implements
		IView, ItemClickListener, ClickListener {

	@AutoGenerated
	private AbsoluteLayout mainLayout;
	@AutoGenerated
	private Button btnClear;
	@AutoGenerated
	private Panel pnlFilter;
	@AutoGenerated
	private GridLayout gridLayout;
	@AutoGenerated
	private TextField tfSalesId;
	@AutoGenerated
	private TextField tfChanel;
	@AutoGenerated
	private Button btnSearch;
	@AutoGenerated
	private Label lblCurrentPage;
	@AutoGenerated
	private PagingComponent pagingComponent;
	@AutoGenerated
	private PromotionConnectedSelectionList promotionConnectedSelectionList;

	/**
	 * The constructor should first build the main layout, set the composition
	 * root and then do any custom initialization.
	 * 
	 * The constructor will not be automatically regenerated by the visual
	 * editor.
	 */
	public PromotionConnectedSelectionPopup(
			PromotionConnectedSelection promotionConnectedSelection) {
		this.promotionConnectedSelection = promotionConnectedSelection;
		countryCode = promotionConnectedSelection.getCountryCode();
		bussinnesLine = promotionConnectedSelection.getBussinessLine();
		initLayout();
	}

	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory
			.getLogger(PromotionConnectedSelectionPopup.class);
	// paging
	private PagingModel model = new PagingModel(0);
	private PromotionConnectedSelection promotionConnectedSelection;

	private String countryCode;
	private String bussinnesLine;

	public PromotionConnectedSelection getPromotionConnectedSelection() {
		if (promotionConnectedSelection == null) {
			promotionConnectedSelection = new PromotionConnectedSelection();
		}
		return promotionConnectedSelection;
	}

	@Override
	public void initLayout() {
		buildMainLayout();
		setCompositionRoot(mainLayout);
		addListener();
		setFilterValue();
		executeSearch();
		initialModelPaging();
	}

	private PromotionConnectedSelection getSearchItem() {
		PromotionConnectedSelection searchItem = new PromotionConnectedSelection();
		searchItem.setChannelValue((String) tfChanel.getValue());
		searchItem.setSalesId((String) tfSalesId.getValue());
		searchItem.setCountryCode(countryCode);
		searchItem.setBussinessLine(bussinnesLine);
		return searchItem;
	}

	private boolean isSearching() {
		PromotionConnectedSelection searchItem = getSearchItem();
		if (!StringUtil.isEmptyOrBlank(searchItem.getChannelValue())
				|| !StringUtil.isEmptyOrBlank(searchItem.getSalesId())
				|| !StringUtil.isEmptyOrBlank(countryCode)) {

			return Boolean.TRUE;
		}
		return Boolean.FALSE;
	}

	private void setFilterValue() {
		PromotionConnectedSelection selection = getPromotionConnectedSelection();
		tfChanel.setValue(selection.getChannelValue());
		tfSalesId.setValue(selection.getSalesId());
	}

	private void updateListBySearching(final int page) {
		PromotionConnectedSelection searchItem = getSearchItem();
		updateList(searchItem, page);
	}

	private void initialModelPaging() {
		model.addPropertyChangeListener("currentPage",
				new PropertyChangeListener() {
					public void propertyChange(final PropertyChangeEvent evt) {
						if (isSearching()) {
							updateListBySearching(model.getCurrentPage());
						} else {
							updatePageNumber();
							updateListByChangePage(model.getCurrentPage());
						}
					}
				});
		pagingComponent.setModel(model);
		updatePageNumber();
	}

	private void updateListByChangePage(final int page) {
		PromotionConnectedSelection selection = new PromotionConnectedSelection();
		selection.setCountryCode(countryCode);
		selection.setChannelValue((String) tfChanel.getValue());
		selection.setSalesId((String) tfSalesId.getValue());

		updateList(selection, page);
	}

	private void updateList(PromotionConnectedSelection selection,
			final int page) {
		IController promotionConnectedSelectionController = ControllerFactory
				.getPromotionConnectedSelectionController();
		final List<BeanItem> beans = promotionConnectedSelectionController
				.getPaginationByCriteria(selection, page,
						promotionConnectedSelectionList.getPageSize());
		promotionConnectedSelectionList.setDataSource(beans);
		// update paging
		final long totalItems = promotionConnectedSelectionController
				.getTotalNumberItemByCriteria(selection);
		final int totalPages = (int) Math.ceil(totalItems
				/ (float) promotionConnectedSelectionList.getPageSize());
		model.setTotalNumberOfPages(totalPages);
		updatePageNumber();
	}

	private void updatePageNumber() {
		lblCurrentPage.setValue(SessionData.getI18N().getMessage(
				Constants.CURRENT_PAGE_VALUE)
				+ model.getCurrentPage());
	}

	private void addListener() {
		promotionConnectedSelectionList.addListener((ItemClickListener) this);
		btnSearch.addListener((ClickListener) this);
		btnClear.addListener((ClickListener) this);
	}

	@Override
	public void reload() {

	}

	private void executeSearch() {
		model.setCurrentPage(1);
		updateListBySearching(1);
	}

	@Override
	public void buttonClick(ClickEvent event) {
		final Button source = event.getButton();

		if (source == btnSearch) {
			LOG.info(DateTimeUtil.getNow()
					+ "Search button is clicked on Promotion connected selection popup. Searching..");
			executeSearch();

		} else if (source == btnClear) {
			LOG.info(DateTimeUtil.getNow()
					+ "Clear button is clicked on Promotion connected selection popup. Clear all filter fields");
			executeClear();

		}
	}

	private void executeClear() {
		tfChanel.setValue("");
		tfSalesId.setValue("");
	}

	@Override
	public void itemClick(ItemClickEvent event) {
		if (event.isDoubleClick()) {
			BeanItem bean = (BeanItem) event.getItem();
			PromotionConnectedSelection selection = getPromotionConnectedSelection();
			PromotionConnectedSelection p = (PromotionConnectedSelection) bean
					.getBean();
			selection.setChannelValue(p.getChannelValue());
			selection.setSalesId(p.getSalesId());
			selection.setCountryCode(p.getCountryCode());
			selection.setChannelCode(p.getChannelCode());
			// Close the popup
			getApplication().getMainWindow().removeWindow(this.getWindow());
		}
	}

	@AutoGenerated
	private AbsoluteLayout buildMainLayout() {
		// common part: create layout
		mainLayout = new AbsoluteLayout();
		mainLayout.setImmediate(Boolean.FALSE);
		mainLayout.setWidth("100%");
		mainLayout.setHeight("100%");
		mainLayout.setMargin(Boolean.FALSE);

		// top-level component properties
		setWidth("100.0%");
		setHeight("100.0%");

		// promotionConnectedSelectionList_1
		promotionConnectedSelectionList = new PromotionConnectedSelectionList();
		promotionConnectedSelectionList.setImmediate(Boolean.FALSE);
		promotionConnectedSelectionList.setWidth("740px");
		promotionConnectedSelectionList.setHeight("300px");
		mainLayout.addComponent(promotionConnectedSelectionList,
				"top:150.0px;left:0.0px;");

		// pagingComponent_1
		pagingComponent = new PagingComponent();
		pagingComponent.setImmediate(Boolean.FALSE);
		pagingComponent.setWidth("-1px");
		pagingComponent.setHeight("-1px");
		mainLayout.addComponent(pagingComponent, "top:490.0px;left:20.0px;");

		// lblCurrentPage
		lblCurrentPage = new Label();
		lblCurrentPage.setImmediate(Boolean.FALSE);
		lblCurrentPage.setWidth("-1px");
		lblCurrentPage.setHeight("-1px");
		lblCurrentPage.setValue("Current Page: ?");
		mainLayout.addComponent(lblCurrentPage, "top:490.0px;left:420.0px;");

		// btnSearch
		btnSearch = new Button();
		btnSearch.setCaption("Search");
		btnSearch.setImmediate(Boolean.TRUE);
		btnSearch.setWidth("336px");
		btnSearch.setHeight("-1px");
		mainLayout.addComponent(btnSearch, "top:100.0px;left:24.0px;");

		// pnlFilter
		pnlFilter = buildPnlFilter();
		mainLayout.addComponent(pnlFilter, "top:0.0px;left:0.0px;");

		// btnClear
		btnClear = new Button();
		btnClear.setCaption("Clear");
		btnClear.setImmediate(Boolean.TRUE);
		btnClear.setWidth("340px");
		btnClear.setHeight("-1px");
		mainLayout.addComponent(btnClear, "top:100.0px;left:380.0px;");

		return mainLayout;
	}

	@AutoGenerated
	private Panel buildPnlFilter() {
		// common part: create layout
		pnlFilter = new Panel();
		pnlFilter.setCaption(SessionData.getI18N().getMessage(Constants.FORM_FILTER));
		pnlFilter.setImmediate(Boolean.FALSE);
		pnlFilter.setWidth("740px");
		pnlFilter.setHeight("90px");

		// gridLayout_1
		gridLayout = buildGridLayout();
		pnlFilter.setContent(gridLayout);

		return pnlFilter;
	}

	@AutoGenerated
	private GridLayout buildGridLayout() {
		// common part: create layout
		gridLayout = new GridLayout();
		gridLayout.setImmediate(Boolean.FALSE);
		gridLayout.setWidth("50.0%");
		gridLayout.setHeight("100.0%");
		gridLayout.setMargin(Boolean.FALSE);
		gridLayout.setColumns(2);

		// tfChanel
		tfChanel = new TextField();
		tfChanel.setCaption("Chanel");
		tfChanel.setImmediate(Boolean.FALSE);
		tfChanel.setWidth("-1px");
		tfChanel.setHeight("-1px");
		tfChanel.setSecret(Boolean.FALSE);
		gridLayout.addComponent(tfChanel, 0, 0);
		gridLayout.setComponentAlignment(tfChanel, new Alignment(48));

		// tfSalesId
		tfSalesId = new TextField();
		tfSalesId.setCaption("Sales ID");
		tfSalesId.setImmediate(Boolean.FALSE);
		tfSalesId.setWidth("-1px");
		tfSalesId.setHeight("-1px");
		tfSalesId.setSecret(Boolean.FALSE);
		gridLayout.addComponent(tfSalesId, 1, 0);
		gridLayout.setComponentAlignment(tfSalesId, new Alignment(48));

		return gridLayout;
	}
}
